package com.huaxiafinance.management.service.impl;

import com.huaxiafinance.management.constant.CommonConstant;
import com.huaxiafinance.management.dto.request.AddScoreResupplymentDto;
import com.huaxiafinance.management.dto.request.QueryScoreResupplymentDto;
import com.huaxiafinance.management.mapper.*;
import com.huaxiafinance.management.model.*;
import com.huaxiafinance.management.service.ScoreResupplymentService;
import com.huaxiafinance.management.util.MessageResult;
import com.huaxiafinance.management.util.ServiceCode;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


/**
 * ScoreResupplymentService 实现类,用来处理积分补发查询及添加业务 Created by hank on 2017/9/8.
 */


@Service("scoreResupplymentService")
public class ScoreResupplymentServiceImpl implements ScoreResupplymentService {

  private static final Logger logger = Logger.getLogger(ScoreResupplymentServiceImpl.class);
  @Autowired
  @SuppressWarnings("SpringJavaAutowiringInspection")
  private ScoreResupplymentMapper scoreResupplymentMapper;
  @Autowired
  @SuppressWarnings("SpringJavaAutowiringInspection")
  private UserMapper userMapper;
  @Autowired
  @SuppressWarnings("SpringJavaAutowiringInspection")
  private FrontUserMapper frontUserMapper;
  @SuppressWarnings("SpringJavaAutowiringInspection")
  @Autowired
  private MemberInfoMapper memberInfoMapper;
  @SuppressWarnings("SpringJavaAutowiringInspection")
  @Autowired
  private MemberGrowthBaseMapper growthBaseMapper;
  @SuppressWarnings("SpringJavaAutowiringInspection")
  @Autowired
  private MemberGradeMapper gradeMapper;
  @Autowired
  @SuppressWarnings("SpringJavaAutowiringInspection")
  private MallScoreRecordMapper mallScoreRecordMapper;

  /**
   * 积分补发记录分页筛选
   */

  public List<ScoreResupplyment> query(QueryScoreResupplymentDto dto) {
    logger.info("积分补发查询请求的参数=============================>" + dto);
    dto.setPage(dto.getPage() == null ? null : (dto.getPage() - 1) * dto.getRows());
    List<ScoreResupplyment> scoreResupplymentList = scoreResupplymentMapper.selectList(dto);
    logger.info("积分补发查询返回的结果=============================>" + scoreResupplymentList);
    return scoreResupplymentList;
  }

  /**
   * 指定条件的积分补发记录条数
   */
  public Integer selectCount(QueryScoreResupplymentDto dto) {
    logger.info("查询积分补发记录数请求的参数=============================>" + dto);
    int count = scoreResupplymentMapper.selectCount(dto);
    logger.info("查询积分补发记录数返回的结果=============================> count:" + count);
    return count;
  }

  /**
   * 单个或多个补发积分
   */
  @Transactional(rollbackFor = Exception.class)
  public MessageResult insert(AddScoreResupplymentDto dto) throws Exception {
    MessageResult result = new MessageResult();
    String phones = dto.getPhones();
    User user = userMapper.selectById(dto.getAdminUserid());
    if (user == null) {
      logger.info("非法的操作者");
      result.setResultMessage(ServiceCode.SCORE_ILLEGAL_OPERATOR);
      return result;
    }
    if (phones == null || "".equals(phones)) {
      result.setResultMessage(ServiceCode.SCORE_ILLEGAL_OPERATOR);
      return result;
    }
    //账户名数组
    String[] phoneArr = phones.split(",");
    //遍历查出所有用户是否存在
    int rows = 0;
    for (String phone : phoneArr) {
      FrontUser frontUser = frontUserMapper.selectUserByPhone(phone);
      if (frontUser == null) {
        if (phoneArr.length == 1) {
          throw new Exception("用户不存在");
        } else {
          throw new Exception("你输入的用户名格式有误");
        }
      }
      //插入补发记录
      ScoreResupplyment sr = new ScoreResupplyment();
      sr.setUserUuid(frontUser.getUserUuid());
      sr.setComment(dto.getComment());
      sr.setGmtCreate(new Date());
      sr.setScore(dto.getScore());
      sr.setAdminUserid(user.getUserId());
      int n = scoreResupplymentMapper.insert(sr);
      if (n < 1) {
        result.setResultMessage(ServiceCode.SCORE_USER_FORMAT_ERROR);
        result.setData(phone);
        return result;
      }
      rows++;
      boolean flag = updateMemberInfo(frontUser.getUserUuid(), dto.getScore(),
          dto.getGiveGrowthValue());
      if (!flag) {
        result.setResultMessage(ServiceCode.SCORE_UPDATE_MEMBERINFO_ERROR);
        result.setData(frontUser.getUserUuid());
        return result;
      }
    }
    result.setSuccessResult();
    result.setData(rows);
    return result;
  }

  /**
   * 解析excel表格,生成FrontUser的list
   */
  public List<String> readExcelFileToList(InputStream inputStream, String fileName)
      throws Exception {
    //账户列表
    List<String> phoneList = new ArrayList<>();
    try {
      //输入流
      //FileInputStream fis = new FileInputStream(fileName);

      //创建工作簿
      Workbook workbook = null;
      if (fileName.toLowerCase().endsWith("xlsx")) {
        workbook = new XSSFWorkbook(inputStream);
      } else if (fileName.toLowerCase().endsWith("xls")) {
        workbook = new HSSFWorkbook(inputStream);
      }
      //获取excel的页数
      int numberOfSheets = 0;

      if (workbook != null) {
        numberOfSheets = workbook.getNumberOfSheets();
      }

      //遍历每一页
      for (int i = 0; i < numberOfSheets; i++) {

        //获取第i页
        Sheet sheet = workbook.getSheetAt(i);
        //遍历每一行
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
          //账户名
          String phone = "";
          //获得行对象
          Row row = rowIterator.next();
          //每行有多个单元格,遍历(这里只有一个)
          Iterator<Cell> cellIterator = row.cellIterator();
          while (cellIterator.hasNext()) {
            //获取单元格对象
            Cell cell = cellIterator.next();
            if (cell.getColumnIndex() > 0) {
              throw new Exception("您上传的附件内容有误,请检查");
            }
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            //check the cell type and process accordingly
            if (phone.equalsIgnoreCase("")) {
              phone = cell.getStringCellValue().trim();
            }
            break;
          }
          phoneList.add(phone);
        }
      }
      inputStream.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
    return phoneList;
  }

  /**
   * 批量补发积分
   */
  @Transactional(rollbackFor = Exception.class)
  public MessageResult batchAdd(InputStream inputStream, AddScoreResupplymentDto dto)
      throws Exception {
    MessageResult result = new MessageResult();
    //查出操作者
    User user = userMapper.selectById(dto.getAdminUserid());
    String fileName = dto.getFileName();
    List<String> phones = null;
    try {
      phones = readExcelFileToList(inputStream, fileName);
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (phones == null || phones.size() < 1) {
      result.setResultMessage(ServiceCode.SCORE_FILE_UPLOAD_ERROR);
      return result;
    }
    int rows = 0;
    for (String phone : phones) {
      FrontUser frontUser = frontUserMapper.selectUserByPhone(phone);
      if (frontUser == null) {
        logger.info("积分补发返回报文" + phone + "用户不存在");
        throw new Exception("您上传的附件内容有误,请检查");
      }
      ScoreResupplyment sr = new ScoreResupplyment();
      sr.setUserUuid(frontUser.getUserUuid());
      sr.setComment(dto.getComment());
      sr.setGmtCreate(new Date());
      sr.setScore(dto.getScore());
      sr.setAdminUserid(user.getUserId());
      int n = scoreResupplymentMapper.insert(sr);
      if (n < 1) {
        result.setResultMessage(ServiceCode.SCORE_USER_FORMAT_ERROR);
        result.setData(phone);
        return result;
      }
      rows++;
      boolean flag = updateMemberInfo(frontUser.getUserUuid(), dto.getScore(),
          dto.getGiveGrowthValue());
      if (!flag) {
        result.setResultMessage(ServiceCode.SCORE_UPDATE_MEMBERINFO_ERROR);
        result.setData(phone);
        return result;
      }
    }
    result.setData(rows);
    result.setSuccessResult();
    return result;
  }

  private boolean updateMemberInfo(String userUuid, Double score, Integer giveGrowthValue) {
    //成长值基数
    MemberGrowthBase memberGrowthBase = growthBaseMapper.selectBaseValue();
    if (memberGrowthBase == null) {
      return false;
    }
    Double baseValue = memberGrowthBase.getBaseValue();
    //更新会员信息
    MemberInfo memberInfo = memberInfoMapper.selectMemberByUserUuid(userUuid);
    if (memberInfo == null) {
      memberInfo = new MemberInfo();
      memberInfo.setCurrentScore((int) Math.round(score));
      memberInfo.setTotalScore((int) Math.round(score));
      if (giveGrowthValue == 1) {
        memberInfo.setGrowthValue(Math.round(score * baseValue) * 1.0);
      } else {
        memberInfo.setGrowthValue(0.0);
      }
      memberInfo.setGradeId(gradeMapper.selectGradeIdByGrowthValue(score * baseValue));
      memberInfo.setUserUuid(userUuid);
      memberInfo.setGmtCreate(new Date());
      if (memberInfoMapper.insertSelective(memberInfo) != 1) {
        logger.error("插入积分会员信息失败---------userUuid" + userUuid);
        return false;
      }
    } else {
      memberInfo.setCurrentScore(memberInfo.getCurrentScore() + (int) Math.round(score));
      memberInfo.setTotalScore(memberInfo.getTotalScore() + (int) Math.round(score));
      if (giveGrowthValue == 1) {
        memberInfo.setGrowthValue(memberInfo.getGrowthValue() + Math.round(score * baseValue));
      }
      //查询成长值对应会员等级
      int gradeId = gradeMapper.selectGradeIdByGrowthValue(memberInfo.getGrowthValue());
      memberInfo.setGradeId(gradeId);
      Integer n = memberInfoMapper.updateByPrimaryKeySelective(memberInfo);
      if (n != 1) {
        logger.error("更新会员信息失败---------userUuid" + userUuid);
        return false;
      }
    }
    //插入获取积分记录
    MallScoreRecord record = new MallScoreRecord();
    record.setUserUuid(memberInfo.getUserUuid());
    record.setModifyType(CommonConstant.ADD_SCORE);
    record.setScore((int) Math.round(score));
    record.setTriggerId(CommonConstant.SCORE_RESUPPLYMENT_TRIGGER_ID);
    record.setGmtModified(new Date());
    if (giveGrowthValue == 1) {
      record.setGrowthValue(Math.round(score * baseValue) * 1.0);
    } else {
      record.setGrowthValue(0.0);
    }
    if (mallScoreRecordMapper.insert(record) == 1) {
      return true;
    }
    logger.error("插入积分变更记录失败---------userUuid" + userUuid);
    return false;
  }
}
